<?php
namespace Lucanswu\Crypt;
use phpseclib\Crypt\AES;
use phpseclib\Crypt\RSA;
class Crypt
{
    public $key = '';
    public $aes = null;
    public $rsa = null;
    public function __construct($key='')
    {
        if ($key) {
            $this->key = $key;
        }
        /*if (is_null($this->aes)) {
            $this->aes = new AES();
        }
        if (is_null($this->rsa)) {
            $this->aes = new RSA();
        }*/
        $this->aes = new AES();
        $this->rsa = new RSA();
    }

    public function encrypt($string, $key='')
    {
        if ($key) {
            $this->key = $key;
        }
        // RSA效率低，加密数据量少的key
        $data['key_encrypted'] = $this->rsa($key);
        // AES效率高，加密传输的数据
        $data['string_encrypted'] = $this->aes($string);
        return $data;
    }

    public function decypt($stringEncrypted, $keyEncrypted)
    {
        // RSA效率低，加密数据量少的key, 重置key
        $this->key = $this->rsa($keyEncrypted, false);
//        var_dump($this->key);
        // AES效率高，加密传输的数据
        return $this->aes($stringEncrypted, false);

    }

    public function aes($string, $encrypt=true)
    {
        $this->aes->setKey(trim($this->key));
        if ($encrypt) {
            return base64_encode($this->aes->encrypt($string));
        } else {
            return $this->aes->decrypt(base64_decode($string));
        }

    }

    public function rsa($string, $encrypt=true)
    {
        $key = $this->getRSAKey();
//        var_dump($key);
        if ($encrypt) {
            $load = $this->rsa->loadKey($key['publickey']);
//            var_dump($load);
            //var_dump($this->>rsa->setPublicKey($key['publickey']));
            $this->rsa->setEncryptionMode(RSA::ENCRYPTION_NONE);

            return base64_encode($this->rsa->encrypt($string));
        } else {
            $load = $this->rsa->loadKey($key['privatekey']);
            $this->rsa->setEncryptionMode(RSA::ENCRYPTION_NONE);
//            var_dump($load);
            return $this->rsa->decrypt(base64_decode($string));
        }

    }

    public function getRSAKey()
    {
//        var_dump(__DIR__);
//        var_dump(__FILE__);
//        $key = ($this->rsa->createKey()) ;
//        $res[] = file_put_contents($key['publickey'],'./rsa/rsa_public.key');
//        $res[] = file_put_contents($key['privatekey'],'./rsa/rsa_private.key');
//        var_dump($res);
        return [
            'publickey' => '-----BEGIN PUBL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+T2/RFmheX9EePr0qCF6QMXr -----END RSA PRIVATE KEY-----',
        ];
    }
}